# -*- coding: utf-8 -*-
#coding=utf-8

import config
from action.user.base import userAction
from model.product import product
from model.category import category
from model.image import image
from model.album import album
from model.company import company

'''
User controller: producing product user views.
'''
class refererAction(userAction):
    def __init__(self, name = '产品管理'):
        userAction.__init__(self, name)

    def GET(self, name):
        if name == 'list':
            return self.list()
        elif name == 'add':
            return self.add()
        elif name == 'delete':
            return self.delete()
        elif name == 'listForBatchDel':
            return self.listForBatchDel()
        elif name == 'edit':
            return self.edit()
        else:
            return self.notFound()

    def POST(self, name):
        if name == 'save':
            return self.save()
        elif name == 'update':
            return self.update()
        elif name == 'deleteBatch':
            return self.deleteBatch()
        else:
            return self.notFound()

    def list(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0

        condition = {'owner':self.userid}
        productObj = product()
        listData = productObj.getOne('COUNT(*) AS `total`',condition)
        totalCount = listData['total']
        productList = productObj.getList('*', condition, 'id asc', str(offset) + ',' + str(count))
        
        pageString = self.getPageStr('/user/product/list', page, count, totalCount)
        self.privData['PRODUCT_LIST'] = productList
        self.privData['PAGE_STRING'] = pageString

        condition = {}
        categoryList = category().getList('*', condition)
        self.privData['CATEGORY_LIST'] = {}
        for i in categoryList:    
            self.privData['CATEGORY_LIST'][i['id']] = i['name']

        return self.display('productList')

    def listForBatchDel(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0

        condition = {'owner':self.userid}
        productObj = product()
        listData = productObj.getOne('COUNT(*) AS `total`',condition)
        totalCount = listData['total']
        productList = productObj.getList('*', condition, 'id asc', str(offset) + ',' + str(count))
        pageString = self.getPageStr('/user/product/list', page, count, totalCount)
        self.privData['PRODUCT_LIST'] = productList
        self.privData['PAGE_STRING'] = pageString

        condition = {}
        categoryList = category().getList('*', condition)
        self.privData['CATEGORY_LIST'] = {}
        for i in categoryList:    
            self.privData['CATEGORY_LIST'][i['id']] = i['name']

        return self.display('productBatchDel')
        
    def delete(self):
        inputParams = self.getInput()
        try:
            condition={'id': inputParams['id']}
            product().delete(condition)
        except Exception, e:
            return self.success(msg='产品删除失败: %s' % e, url=self.makeUrl('/user/product/list'))

        return self.success(msg='产品删除成功', url=self.makeUrl('/user/product/list'))

    def deleteBatch(self):
        inputParams = self.getInput()
        try:
            condition = ' id IN (' + inputParams['delitems'] +')'
            product().delete(condition)
        except Exception, e:
            return self.error(msg='对象删除失败: %s' % e, url=self.makeUrl('/user/product/list'))

        return self.success(msg='对象删除成功', url=self.makeUrl('/user/product/list'))

    def edit(self):
        inputParams = self.getInput()
        condition={'id': inputParams['id']}
        productObj = product().getOne('*', condition)
        if not productObj:
            return self.error(msg = '该产品不存在', url=self.makeUrl('/user/product/list'))

        categoryList = self.getProdCats()
        self.privData['CATEGORY_LIST'] = {}
        for item in categoryList:
            self.privData['CATEGORY_LIST'][item['id']] = item['name']

        self.privData['PRODUCT'] = productObj
        self.privData['CURRENT_IMG'] = productObj["picture"]

        condition = {'owner':self.userid}
        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        companyList = company().getList('*', condition)
        self.privData['COMPANY_LIST'] = {}
        for item in companyList:
            self.privData['COMPANY_LIST'][item['id']] = item['name']

        self.privData['IMG_URL_LIST'] = {};
        self.privData['IMG_ALBUM_LIST'] = {}
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc'] 
                self.privData['IMG_URL_LIST'][img['id']] = self.imageUrl(img['id'])

        self.privData['CURRENT_ALBUM'] = 1
        self.privData['SUBMIT_NAME'] = "picture"

        return self.display('productEdit')

    def update(self):
        inputParams= self.getInput()  
        data = {
            'name':          inputParams['name'],
            'price':         inputParams['price'],
            'discount':      inputParams['discount'],
            'desc':          self.htmlunquote(inputParams['desc']),
            'company':       inputParams['company'],
            'longitude':     inputParams['longitude'],
            'latitude':      inputParams['latitude'],
            'picture':       inputParams['picture'],
            'category':      inputParams['category'],
            'region':        inputParams['region'],
            'telephone':     inputParams['telephone'],
            'contact':       inputParams['contact'],
            'email':         inputParams['email'],
            'rank':          inputParams['rank'],
            'address':       inputParams['address'],
            'owner':         self.userid,
        }
        try:
            condition = {'id': inputParams['id']}
            product().update(data,condition)
        except Exception, e:
            return self.error(msg = '产品修改失败: %s' % e, url=self.makeUrl('/user/product/list'))

        return self.success('产品修改成功', url=self.makeUrl('/user/product/list'))

    def add(self):
        categoryList = self.getProdCats()

        self.privData['CATEGORY_LIST'] = {}
        for item in categoryList:
            self.privData['CATEGORY_LIST'][item['id']] = item['name']

        condition = {'owner':self.userid}
        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        companyList = company().getList('*', condition)
        self.privData['COMPANY_LIST'] = {}
        for item in companyList:
            self.privData['COMPANY_LIST'][item['id']] = item['name']

        self.privData['IMG_URL_LIST'] = {};
        self.privData['IMG_ALBUM_LIST'] = {}
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc'] 
                self.privData['IMG_URL_LIST'][img['id']] = self.imageUrl(img['id'])

        self.privData['CURRENT_ALBUM'] = 1
        self.privData['CURRENT_IMG'] = 1
        self.privData['SUBMIT_NAME'] = "picture"

        return self.display('productAdd')


    def save(self):
        inputParams= self.getInput()
        data = {
            'name':          inputParams['name'],
            'price':         inputParams['price'],
            'discount':      inputParams['discount'],
            'desc':          self.htmlunquote(inputParams['desc']),
            'company':       inputParams['company'],
            'longitude':     inputParams['longitude'],
            'latitude':      inputParams['latitude'],
            'picture':       inputParams['picture'],
            'category':      inputParams['category'],
            'region':        inputParams['region'],
            'telephone':     inputParams['telephone'],
            'contact':       inputParams['contact'],
            'email':         inputParams['email'],
            'rank':          inputParams['rank'],
            'address':       inputParams['address'],
            'owner':         self.userid,
        }
        try:
            product().insert(data)
        except Exception, e:
            return self.error(msg = '新增产品失败: %s' % e, url=self.makeUrl('/user/product/list'))

        return self.success('新增产品成功', url=self.makeUrl('/user/product/list'))

